import type { routesInt } from '@/routers/types'
import { h, type Component } from 'vue'
import { Icon } from '@iconify/vue'
import { NIcon } from 'naive-ui'
import { RouterLink } from 'vue-router'

export function renderIcon(icon: string | Component) {
  if (typeof icon === 'string') {
    return () => h(NIcon, null, { default: () => h(Icon, { icon }) })
  }
  return () => h(NIcon, null, { default: () => h(icon) })
}

function randerLabel(item: routesInt) {
  if (!item.children) {
    return () =>
      h(
        RouterLink,
        {
          to: {
            path: item.path,
          },
        },
        { default: () => item.name },
      )
  } else {
    // 父级菜单没有RouterLink
    return () => item.name
  }
}

function transformMenuItem(menuItem: routesInt) {
  const transformed = {
    ...menuItem,
    label: randerLabel(menuItem),
    key: menuItem.path,
    icon: renderIcon(menuItem.meta?.icon as string),
  }
  if (menuItem.children) {
    transformed.children = menuItem.children.map(transformMenuItem)
  }
  return transformed
}

export function transformRoutes(menu: any[]) {
  return menu.map(transformMenuItem)
}
